package com.pubinfo.passbook.data.service.impl;

import cn.hutool.core.lang.Snowflake;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.pubinfo.passbook.common.entity.TSynWriteoffInfo;
import com.pubinfo.passbook.common.entity.TWiteoffInfoPassbook;
import com.pubinfo.passbook.common.mapper.TSourcePassbookReimburseMapper;
import com.pubinfo.passbook.common.mapper.TSynWriteoffInfoMapper;
import com.pubinfo.passbook.common.mapper.TWiteoffInfoPassbookMapper;
import com.pubinfo.passbook.common.model.bo.valueAddedTax.*;
import com.pubinfo.passbook.common.model.dto.financial.ClaimRecord;
import com.pubinfo.passbook.common.model.dto.financial.FeedbackParam;
import com.pubinfo.passbook.common.service.master.ITSynWriteoffInfoService;
import com.pubinfo.passbook.common.service.master.TSourcePassbookReimburseService;
import com.pubinfo.passbook.common.service.master.impl.TSynWriteoffInfoServiceImpl;
import com.pubinfo.passbook.common.service.request.financial.RequestFinancialServer;
import com.pubinfo.passbook.data.service.SynWriteoffInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class SynWriteoffInfoServiceImpl implements SynWriteoffInfoService {

    @Resource
    InputParamHeader inputParamHeader;
    @Autowired
    TWiteoffInfoPassbookMapper tWiteoffInfoPassbookMapper;
    @Autowired
    TSynWriteoffInfoMapper tSynWriteoffInfoMapper;
    @Autowired
    ITSynWriteoffInfoService tSynWriteoffInfoService;
    @Autowired
    RequestFinancialServer requestFinancialServer;
    @Autowired
    TSourcePassbookReimburseMapper tSourcePassbookReimburseMapper;

    @Override
    public Boolean synWriteoffInfo(InputParamBody inputParamBody) throws UnirestException {
        String json = sendPostSynWriteoffInfo(inputParamBody);
        OutParam outParam = JSONObject.parseObject(json, OutParam.class);
        List<TSynWriteoffInfo> tSynWriteoffInfos = new ArrayList<>();
        for (OutParamItem outParamItem : outParam.getItems()) {
            tSynWriteoffInfos.add(new TSynWriteoffInfo(outParamItem));
            if(CollectionUtils.isEmpty(tWiteoffInfoPassbookMapper.selectEInvoiceId(outParamItem.getWriteoffInstanceCode())))
            {
                tWiteoffInfoPassbookMapper.insertTwiteoffInfoPassbook(outParamItem.getWriteoffInstanceCode(), outParamItem.getInvoiceInfos());
            }
        }
        if (CollectionUtils.isNotEmpty(tSynWriteoffInfos)) {
//            return true;
            return tSynWriteoffInfoService.saveOrUpdateBatch(tSynWriteoffInfos);
        } else {
            return true;
        }
    }

    @Override
    public Boolean updateWriteoffInfo() throws UnirestException {
        List<String> writeoffInstanceCodes=tSynWriteoffInfoMapper.selectWriteoffInfoNeedSyn();
        InputParamBody inputParamBody=new InputParamBody();
        for(String writeoffInstanceCode:writeoffInstanceCodes)
        {
            inputParamBody.getItems().add(new InputParamItem(writeoffInstanceCode));
        }
        String json = sendPostSynWriteoffInfo(inputParamBody);
        OutParam outParam = JSONObject.parseObject(json, OutParam.class);
        List<TSynWriteoffInfo> tSynWriteoffInfos = new ArrayList<>();
        for (OutParamItem outParamItem : outParam.getItems()) {
            tSynWriteoffInfos.add(new TSynWriteoffInfo(outParamItem));
        }
        if (CollectionUtils.isNotEmpty(tSynWriteoffInfos)) {
//            return true;
            return tSynWriteoffInfoService.saveOrUpdateBatch(tSynWriteoffInfos);
        } else {
            return true;
        }
    }

    @Override
    public Boolean synWriteoffInfoList(Date startTime, Date endTime) throws UnirestException, ParseException {
        Calendar tempStart = Calendar.getInstance();
        tempStart.setTime(startTime);
        Calendar tempEnd = Calendar.getInstance();
        tempEnd.setTime(endTime);
        tempEnd.add(Calendar.DAY_OF_YEAR, 1);// 日期加1(包含结束)
        while (tempStart.before(tempEnd)) {
            synWriteoffInfo(new InputParamBody(tempStart.getTime()));
            tempStart.add(Calendar.DAY_OF_YEAR, 1);
        }
        return true;
    }

    @Override
    public Boolean synYesterdayWriteoffInfo() throws UnirestException {
        Calendar temp = Calendar.getInstance();
        return synWriteoffInfo(new InputParamBody(temp.getTime()));
    }

    @Override
    public void claimFeedback() {
        List<TSynWriteoffInfo> tSynWriteoffInfos=tSynWriteoffInfoMapper.selectNeedFeedback();
        for(TSynWriteoffInfo tSynWriteoffInfo:tSynWriteoffInfos)
        {
            if(requestFinancialServer.claimFeedback(createFeedbackParam(tSynWriteoffInfo)))
            {
                tSynWriteoffInfo.setNeedFeedback(true);
                tSynWriteoffInfoService.saveOrUpdate(tSynWriteoffInfo);
                tSourcePassbookReimburseMapper.insertByWriteoffInstanceCode(tSynWriteoffInfo.getWriteoffInstanceCode());
            }
        }
    }

    @Override
    public void claimFeedbackByWriteoffInstanceCode(String writeoffInstanceCode) {
        TSynWriteoffInfo tSynWriteoffInfo=tSynWriteoffInfoService.getById(writeoffInstanceCode);
        requestFinancialServer.claimFeedback(createFeedbackParam(tSynWriteoffInfo));
        tSynWriteoffInfo.setNeedFeedback(true);
        tSynWriteoffInfoService.saveOrUpdate(tSynWriteoffInfo);
        tSourcePassbookReimburseMapper.insertByWriteoffInstanceCode(writeoffInstanceCode);
    }


    private FeedbackParam createFeedbackParam(TSynWriteoffInfo tSynWriteoffInfo)
    {
        FeedbackParam feedbackParam=new FeedbackParam();
        List<ClaimRecord> claimRecords=new ArrayList<>();
        List<TWiteoffInfoPassbook> tWiteoffInfoPassbooks=tWiteoffInfoPassbookMapper.selectEInvoiceIdByWriteoffInstanceCode(tSynWriteoffInfo.getWriteoffInstanceCode());
        String remark=null;
//        if(tWiteoffInfoPassbooks.size()>1)
//        {
//            remark="报销金额"+tSynWriteoffInfo.getWriteoffSum()+"元，票据号码分别为";
//            for(TWiteoffInfoPassbook tWiteoffInfoPassbook:tWiteoffInfoPassbooks)
//            {
//                remark+=tWiteoffInfoPassbook.getEInvoiceId()+"、";
//            }
//            remark=remark.substring(0,remark.length()-1)+"。";
//        }
        for(TWiteoffInfoPassbook tWiteoffInfoPassbook:tWiteoffInfoPassbooks)
        {
            claimRecords.add(new ClaimRecord(tWiteoffInfoPassbook.getEInvoiceId(),remark,tSynWriteoffInfo.getWriteoffSum()));
        }
        feedbackParam.setAccNumber(tSynWriteoffInfo.getWriteoffInstanceCode());
        feedbackParam.setAccDate(tSynWriteoffInfo.getLedgerDate());
        feedbackParam.setClaimRecords(claimRecords);
        return feedbackParam;
    }

    private String sendPostSynWriteoffInfo(InputParamBody inputParamBody) throws UnirestException {
        //Unirest.setTimeouts(0, 0);
        inputParamHeader.setMsgId(new Snowflake(1, 1).nextId());
        String s = JSONObject.toJSON(inputParamBody).toString();
        HttpResponse<String> response = Unirest.post(inputParamHeader.getUrl())
                .header("X-APP-ID", inputParamHeader.getXAppId())
                .header("X-APP-KEY", inputParamHeader.getXAppKey())
                .header("msgId", inputParamHeader.getMsgId().toString())
                .header("provinceCode", inputParamHeader.getProvinceCode())
                .header("systemCode", inputParamHeader.getSystemCode())
                .body(JSONObject.toJSON(inputParamBody).toString()).asString();
        return response.getBody();
    }
}
